package cz.muni.fi.pa165.sportclubmanager.service;

import cz.muni.fi.pa165.sportclubmanager.dao.PlayerOnRosterDAO;
import cz.muni.fi.pa165.sportclubmanager.dao.TeamDAO;
import cz.muni.fi.pa165.sportclubmanager.dto.AgeCategoryDTO;
import cz.muni.fi.pa165.sportclubmanager.dto.AgeCategoryDTOMapping;
import cz.muni.fi.pa165.sportclubmanager.dto.TeamDTO;
import cz.muni.fi.pa165.sportclubmanager.dto.TeamDTOMapping;
import cz.muni.fi.pa165.sportclubmanager.entity.PlayerOnRoster;
import cz.muni.fi.pa165.sportclubmanager.entity.Team;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/*
 * @author xondrusk
 */

@Service
public class TeamServiceImpl implements TeamService {
    
    @Autowired
    private PlayerOnRosterDAO playerOnRosterDAO;
    
    private TeamDAO teamDao;
    
    @Autowired
    void setTeamDao(TeamDAO teamDao){
        this.teamDao = teamDao;
    }

    @Override
    @Transactional   
    @Secured({"ROLE_ADMIN"})
    public void create(TeamDTO t) {
        teamDao.create(TeamDTOMapping.toEntity(t));
    }

    @Override
    @Transactional    
    @Secured({"ROLE_ADMIN"})
    public void update(TeamDTO t) {
        teamDao.update(TeamDTOMapping.toEntity(t));
    }

    @Override
    @Transactional    
    @Secured({"ROLE_ADMIN"})
    public void remove(TeamDTO t) {
        Team team = TeamDTOMapping.toEntity(t);
        List<PlayerOnRoster> rosters = playerOnRosterDAO.findAllWithTeam(team);
        for (PlayerOnRoster roster : rosters) {   
            playerOnRosterDAO.remove(roster);
        }
        teamDao.remove(TeamDTOMapping.toEntity(t));
    }

    @Override
    @Transactional    
    @Secured({"ROLE_USER","ROLE_ADMIN"})        
    public TeamDTO find(Long id) {
        return TeamDTOMapping.toDto(teamDao.find(id));
    }

    @Override
    @Transactional    
    @Secured({"ROLE_USER","ROLE_ADMIN"})        
    public List<TeamDTO> findAll() {
        return convertEntitiesToDtos(teamDao.findAll());
    }

    @Override
    @Transactional    
    @Secured({"ROLE_USER","ROLE_ADMIN"})        
    public List<TeamDTO> findByAgeCategory(AgeCategoryDTO ageCategory) {
        return convertEntitiesToDtos(teamDao.findByAgeCategory(AgeCategoryDTOMapping.toEntity(ageCategory)));        
    }
        
    private List<TeamDTO> convertEntitiesToDtos(List<Team> teams){
        List<TeamDTO> teamDtos = new ArrayList<TeamDTO>();
        for(Team team : teams){
            teamDtos.add(TeamDTOMapping.toDto(team));
        }
        return teamDtos;
    }
    
}
